import { getServerCachApi, creatServerCachApi } from '@src/api/GuideApi'
import * as localForage from 'localforage'

localForage.config({
  name: 'shb-pc-fe'
})

const isCatch: any = {}
const noServerCacheValue = '----no_server_cache----'

async function setServerCach<T, K>(key: string, defaultValue: T, module: any, storageKey: string): Promise<T | K | string | null> {
  try {
    localForage.config({
      storeName: module
    })
    await localForage.setItem(`servercache-${module}-${storageKey}`, defaultValue)
  } catch (err) { }

  return await creatServerCachApi({
    "type": storageKey,
    "step": 1,
    "isComplete": 1,
    "userConfig": JSON.stringify(defaultValue),
  })
}

async function getServerCach<T, K>(key: string, defaultValue: K, module: any, storageKey: string, use24HoursCache = true): Promise<T | K | string | null> {
  try {
    localForage.config({
      storeName: module
    })
  } catch (err) { }

  // 前端缓存 24小时
  try {
    const date: any = await localForage.getItem(`servercache-${module}-${storageKey}-time`)
    // 是否使用前端24小时的缓存数据，默认使用
    if (use24HoursCache && date && (new Date().getTime() - Number(date)) < 86400000) {
      const value: any = await localForage.getItem(`servercache-${module}-${storageKey}`)
      if (value && value != noServerCacheValue) {
        return Promise.resolve(value)
      }
      if(value && value == noServerCacheValue){
        return Promise.resolve(null)
      }
    }
  } catch (err) {
    return Promise.resolve(null)
  }

  // 避免接口重复请求
  try {
    if (isCatch[`${module}-${storageKey}`]) {
      const value: any = await localForage.getItem(`servercache-${module}-${storageKey}`)
      if (value && value != noServerCacheValue) {
        return Promise.resolve(value)
      }
      if(value && value == noServerCacheValue){
        return Promise.resolve(null)
      }
      return Promise.resolve(null)
    }
  } catch (err) {
    return Promise.resolve(null)
  }

  // 从服务端拿到数据并缓存到前端
  try {
    const res = await getServerCachApi(storageKey)
    if(res.data && res.data.length === 0){
      isCatch[`${module}-${storageKey}`] = true
      await localForage.setItem(`servercache-${module}-${storageKey}`, noServerCacheValue)
      await localForage.setItem(`servercache-${module}-${storageKey}-time`, new Date().getTime())
      return Promise.resolve(null)
    }
    if (!res.data || !res.data.length || !res.data[0].userConfig) {
      return Promise.resolve(null)
    } else {
      isCatch[`${module}-${storageKey}`] = true
      await localForage.setItem(`servercache-${module}-${storageKey}`, JSON.parse(res.data[0].userConfig))
      await localForage.setItem(`servercache-${module}-${storageKey}-time`, new Date().getTime())
      return Promise.resolve(JSON.parse(res.data[0].userConfig))
    }
  } catch (err) {
    return Promise.resolve(null)
  }
}

export {
  setServerCach,
  getServerCach,
}